package com.bi.controller;

import com.bi.common.PageResult;
import com.bi.common.Result;
import com.bi.dto.CreateWideTableDTO;
import com.bi.dto.WideTableDataQueryDTO;
import com.bi.dto.WideTableQueryDTO;
import com.bi.entity.WideTable;
import com.bi.service.WideTableService;
import com.bi.vo.WideTableDataVO;
import com.bi.vo.WideTableFieldVO;
import com.bi.vo.WideTableVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 数据宽表控制器
 * 
 * @author BI Platform Team
 * @since 1.0.0
 */
@Slf4j
@Api(tags = "数据宽表管理")
@RestController
@RequestMapping("/wide-tables")
@Validated
public class WideTableController {

    @Autowired
    private WideTableService wideTableService;

    @ApiOperation("创建数据宽表")
    @PostMapping
    @PreAuthorize("hasAuthority('wide_table:create')")
    public Result<Long> createWideTable(
            @ApiParam("创建数据宽表请求") @Valid @RequestBody CreateWideTableDTO createDTO) {
        
        // 从安全上下文获取当前用户（这里简化处理）
        String currentUser = getCurrentUser();
        
        Long wideTableId = wideTableService.createWideTable(createDTO, currentUser);
        return Result.success("数据宽表创建成功", wideTableId);
    }

    @ApiOperation("更新数据宽表")
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('wide_table:edit')")
    public Result<Boolean> updateWideTable(
            @ApiParam("宽表ID") @PathVariable @NotNull Long id,
            @ApiParam("更新数据宽表请求") @Valid @RequestBody CreateWideTableDTO createDTO) {
        
        String currentUser = getCurrentUser();
        boolean updated = wideTableService.updateWideTable(id, createDTO, currentUser);
        return Result.success("数据宽表更新成功", updated);
    }

    @ApiOperation("删除数据宽表")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('wide_table:delete')")
    public Result<Boolean> deleteWideTable(@ApiParam("宽表ID") @PathVariable @NotNull Long id) {
        String currentUser = getCurrentUser();
        boolean deleted = wideTableService.deleteWideTable(id, currentUser);
        return Result.success("数据宽表删除成功", deleted);
    }

    @ApiOperation("根据ID查询数据宽表详情")
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('wide_table:view')")
    public Result<WideTableVO> getWideTableById(@ApiParam("宽表ID") @PathVariable @NotNull Long id) {
        WideTableVO wideTableVO = wideTableService.getWideTableById(id);
        return Result.success(wideTableVO);
    }

    @ApiOperation("分页查询数据宽表")
    @GetMapping
    @PreAuthorize("hasAuthority('wide_table:view')")
    public Result<PageResult<WideTableVO>> getWideTablePage(@Valid WideTableQueryDTO queryDTO) {
        PageResult<WideTableVO> pageResult = wideTableService.getWideTablePage(queryDTO);
        return Result.success(pageResult);
    }

    @ApiOperation("查询用户可访问的数据宽表列表")
    @GetMapping("/accessible")
    @PreAuthorize("hasAuthority('wide_table:view')")
    public Result<List<WideTableVO>> getAccessibleWideTableList() {
        String currentUser = getCurrentUser();
        List<WideTableVO> wideTableList = wideTableService.getAccessibleWideTableList(currentUser);
        return Result.success(wideTableList);
    }

    @ApiOperation("根据宽表ID查询字段列表")
    @GetMapping("/{id}/fields")
    @PreAuthorize("hasAuthority('wide_table:view')")
    public Result<List<WideTableFieldVO>> getWideTableFields(
            @ApiParam("宽表ID") @PathVariable @NotNull Long id) {
        List<WideTableFieldVO> fields = wideTableService.getWideTableFields(id);
        return Result.success(fields);
    }

    @ApiOperation("更新宽表字段配置")
    @PutMapping("/{id}/fields")
    @PreAuthorize("hasAuthority('wide_table:edit')")
    public Result<Boolean> updateWideTableFields(
            @ApiParam("宽表ID") @PathVariable @NotNull Long id,
            @ApiParam("字段配置列表") @Valid @RequestBody List<CreateWideTableDTO.WideTableFieldDTO> fields) {
        
        String currentUser = getCurrentUser();
        boolean updated = wideTableService.updateWideTableFields(id, fields, currentUser);
        return Result.success("字段配置更新成功", updated);
    }

    @ApiOperation("初始化在线数据宽表索引")
    @PostMapping("/{id}/index")
    @PreAuthorize("hasAuthority('wide_table:edit')")
    public Result<Boolean> initOnlineWideTableIndex(
            @ApiParam("宽表ID") @PathVariable @NotNull Long id) {
        boolean initialized = wideTableService.initOnlineWideTableIndex(id);
        return Result.success("索引初始化成功", initialized);
    }

    @ApiOperation("查询宽表数据")
    @PostMapping("/data/query")
    @PreAuthorize("hasAuthority('wide_table:view')")
    public Result<WideTableDataVO> queryWideTableData(
            @ApiParam("查询条件") @Valid @RequestBody WideTableDataQueryDTO queryDTO) {
        WideTableDataVO dataVO = wideTableService.queryWideTableData(queryDTO);
        return Result.success(dataVO);
    }

    @ApiOperation("聚合查询宽表数据")
    @PostMapping("/data/aggregate")
    @PreAuthorize("hasAuthority('wide_table:view')")
    public Result<Map<String, Object>> aggregateWideTableData(
            @ApiParam("查询条件") @Valid @RequestBody WideTableDataQueryDTO queryDTO) {
        Map<String, Object> aggregateResult = wideTableService.aggregateWideTableData(queryDTO);
        return Result.success(aggregateResult);
    }

    @ApiOperation("导出宽表数据")
    @PostMapping("/data/export")
    @PreAuthorize("hasAuthority('wide_table:view')")
    public Result<String> exportWideTableData(
            @ApiParam("查询条件") @Valid @RequestBody WideTableDataQueryDTO queryDTO) {
        String filePath = wideTableService.exportWideTableData(queryDTO);
        return Result.success("数据导出成功", filePath);
    }

    @ApiOperation("获取宽表字段统计信息")
    @GetMapping("/{id}/fields/{fieldName}/stats")
    @PreAuthorize("hasAuthority('wide_table:view')")
    public Result<WideTableDataVO.FieldStats> getFieldStats(
            @ApiParam("宽表ID") @PathVariable @NotNull Long id,
            @ApiParam("字段名称") @PathVariable @NotNull String fieldName) {
        WideTableDataVO.FieldStats stats = wideTableService.getFieldStats(id, fieldName);
        return Result.success(stats);
    }

    @ApiOperation("检查宽表名称是否可用")
    @GetMapping("/check-name")
    @PreAuthorize("hasAuthority('wide_table:view')")
    public Result<Boolean> checkWideTableName(
            @ApiParam("宽表名称") @RequestParam String name,
            @ApiParam("排除的ID") @RequestParam(required = false) Long excludeId) {
        boolean available = wideTableService.isWideTableNameAvailable(name, excludeId);
        return Result.success(available);
    }

    @ApiOperation("激活/停用数据宽表")
    @PutMapping("/{id}/status")
    @PreAuthorize("hasAuthority('wide_table:edit')")
    public Result<Boolean> updateWideTableStatus(
            @ApiParam("宽表ID") @PathVariable @NotNull Long id,
            @ApiParam("状态") @RequestParam WideTable.WideTableStatus status) {
        String currentUser = getCurrentUser();
        boolean updated = wideTableService.updateWideTableStatus(id, status, currentUser);
        return Result.success("状态更新成功", updated);
    }

    @ApiOperation("同步宽表结构到Elasticsearch")
    @PostMapping("/{id}/sync")
    @PreAuthorize("hasAuthority('wide_table:edit')")
    public Result<Boolean> syncWideTableToEs(@ApiParam("宽表ID") @PathVariable @NotNull Long id) {
        boolean synced = wideTableService.syncWideTableToEs(id);
        return Result.success("同步成功", synced);
    }

    @ApiOperation("获取宽表数据总数")
    @GetMapping("/{id}/data/count")
    @PreAuthorize("hasAuthority('wide_table:view')")
    public Result<Long> getWideTableDataCount(@ApiParam("宽表ID") @PathVariable @NotNull Long id) {
        long count = wideTableService.getWideTableDataCount(id);
        return Result.success(count);
    }

    @ApiOperation("清空宽表数据")
    @DeleteMapping("/{id}/data")
    @PreAuthorize("hasAuthority('wide_table:delete')")
    public Result<Boolean> clearWideTableData(@ApiParam("宽表ID") @PathVariable @NotNull Long id) {
        String currentUser = getCurrentUser();
        boolean cleared = wideTableService.clearWideTableData(id, currentUser);
        return Result.success("数据清空成功", cleared);
    }

    /**
     * 获取当前用户（简化实现）
     * 实际项目中应该从Spring Security上下文中获取
     */
    private String getCurrentUser() {
        // 这里简化处理，实际项目中应该从SecurityContextHolder中获取当前用户
        return "admin";
    }
}